<?php

namespace app\admin\controller\store;

use Throwable;
use app\common\controller\Backend;

/**
 * 小店订单
 */
class Order extends Backend
{
    /**
     * Order模型对象
     * @var object
     * @phpstan-var \app\admin\model\store\Order
     */
    protected object $model;

    protected array|string $preExcludeFields = ['order_id', 'aftersale_detail'];

    protected array $withJoinTable = ['shopUser','store'];

    protected string|array $quickSearchField = ['order_id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\store\Order();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit)->each(function ($item) {
                $item->product_infos = json_decode($item->product_infos, true);
                $item->sharer_info = json_decode($item->sharer_info, true);
                $item->sku_sharer_infos = json_decode($item->sku_sharer_infos, true);
                $item->aftersale_detail = json_decode($item->aftersale_detail, true);
                $item->delivery_product_info = json_decode($item->delivery_product_info, true);
                $item->pay_info = json_decode($item->pay_info, true);

            });
        $res->visible(['store' => ['name'],'shopUser' => ['nickname']]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }
        if(isset($row->product_infos)){
            $row->product_infos = json_decode($row->product_infos, true);
            foreach ($row->product_infos as $key => $value) {
                $product_infos[$key] = $value;
                $str = '';
                if($value['sku_attrs']){
                    foreach ($value['sku_attrs'] as $kk => $vv) {
                        $str .= $vv['attr_key'].':'.$vv['attr_value'].'|';
                    }
                }
                $product_infos[$key]['sku_attrs'] = $str;
            }
            $row->product_infos = $product_infos;
        }
        if(isset($row->sharer_info)){
            $row->sharer_info = json_decode($row->sharer_info, true);
            $sharer_info = $row->sharer_info;
            if($row->sharer_info['sharer_type'] == 1){
                $sharer_info['sharer_type'] = '普通分享员';
            }elseif ($row->sharer_info['sharer_type'] == 2){
                $sharer_info['sharer_type'] = '店铺分享员';
            }
            if($row->sharer_info['handling_progress'] == 1){
                $sharer_info['handling_progress'] = '解析完成';
            }elseif ($row->sharer_info['handling_progress'] == 2){
                $sharer_info['handling_progress'] = '解析中';
            }

            if($row->sharer_info['share_scene'] == 1){
                $sharer_info['share_scene'] = '直播间';
            }elseif ($row->sharer_info['share_scene'] == 2){
                $sharer_info['share_scene'] = '橱窗';
            }elseif ($row->sharer_info['share_scene'] == 3){
                $sharer_info['share_scene'] = '短视频';
            }elseif ($row->sharer_info['share_scene'] == 4){
                $sharer_info['share_scene'] = '视频号主页';
            }elseif ($row->sharer_info['share_scene'] == 5){
                $sharer_info['share_scene'] = '商品详情页';
            }elseif ($row->sharer_info['share_scene'] == 6){
                $sharer_info['share_scene'] = '带商品的公众号文章';
            }elseif ($row->sharer_info['share_scene'] == 7){
                $sharer_info['share_scene'] = '商品链接';
            }elseif ($row->sharer_info['share_scene'] == 8){
                $sharer_info['share_scene'] = '商品二维码';
            }elseif ($row->sharer_info['share_scene'] == 9){
                $sharer_info['share_scene'] = '商品短链';
            }elseif ($row->sharer_info['share_scene'] == 10){
                $sharer_info['share_scene'] = '分享直播间';
            }elseif ($row->sharer_info['share_scene'] == 11){
                $sharer_info['share_scene'] = '分享预约直播间';
            }elseif ($row->sharer_info['share_scene'] == 12){
                $sharer_info['share_scene'] = '视频号橱窗的短链';
            }elseif ($row->sharer_info['share_scene'] == 13){
                $sharer_info['share_scene'] = '视频号橱窗的二维码';
            }
            $row->sharer_info = $sharer_info;
        }
        if(isset($row->sku_sharer_infos)){
            $row->sku_sharer_infos = json_decode($row->sku_sharer_infos, true);
            foreach ($row->sku_sharer_infos as $key => $value) {
                $sku_sharer_infos[$key] = $value;
                if($value['sharer_type'] == 1){
                    $sku_sharer_infos[$key]['sharer_type'] = '普通分享员';
                }elseif ($value['sharer_type'] == 2){
                    $sku_sharer_infos[$key]['sharer_type'] = '店铺分享员';
                }

                if($value['share_scene'] == 1){
                    $sku_sharer_infos[$key]['share_scene'] = '直播间';
                }elseif ($value['share_scene'] == 2){
                    $sku_sharer_infos[$key]['share_scene'] = '橱窗';
                }elseif ($value['share_scene'] == 3){
                    $sku_sharer_infos[$key]['share_scene'] = '短视频';
                }elseif ($value['share_scene'] == 4){
                    $sku_sharer_infos[$key]['share_scene'] = '视频号主页';
                }elseif ($value['share_scene'] == 5){
                    $sku_sharer_infos[$key]['share_scene'] = '商品详情页';
                }elseif ($value['share_scene'] == 6){
                    $sku_sharer_infos[$key]['share_scene'] = '带商品的公众号文章';
                }elseif ($value['share_scene'] == 7){
                    $sku_sharer_infos[$key]['share_scene'] = '商品链接';
                }elseif ($value['share_scene'] == 8){
                    $sku_sharer_infos[$key]['share_scene'] = '商品二维码';
                }elseif ($value['share_scene'] == 9){
                    $sku_sharer_infos[$key]['share_scene'] = '商品短链';
                }elseif ($value['share_scene'] == 10){
                    $sku_sharer_infos[$key]['share_scene'] = '分享直播间';
                }elseif ($value['share_scene'] == 11){
                    $sku_sharer_infos[$key]['share_scene'] = '分享预约直播间';
                }elseif ($value['share_scene'] == 12){
                    $sku_sharer_infos[$key]['share_scene'] = '视频号橱窗的短链';
                }elseif ($value['share_scene'] == 13){
                    $sku_sharer_infos[$key]['share_scene'] = '视频号橱窗的二维码';
                }
            }
            $row->sku_sharer_infos = $sku_sharer_infos;
        }
        if(isset($row->aftersale_detail)){
            $row->aftersale_detail = json_decode($row->aftersale_detail, true);
        }
        if(isset($row->delivery_product_info)){
            $row->delivery_product_info = json_decode($row->delivery_product_info, true);
            foreach ($row->delivery_product_info as $key => $value) {
                $delivery_product_info[$key] = $value;
                $str = '';
                if(isset($value['product_infos'])){
                    foreach ($value['product_infos'] as $kk => $vv) {
                        $str .= '商品id:'.$vv['product_id'].' sku_id:'.$vv['sku_id'].' 商品数量:'.$vv['product_cnt'].'|';
                    }
                }
                $delivery_product_info[$key]['delivery_time'] = date('Y-m-d H:i:s',$value['delivery_time']);
                $delivery_product_info[$key]['product_infos'] = $str;
            }
            $row->delivery_product_info = $delivery_product_info;
        }
        if(isset($row->pay_info)){
            $row->pay_info = json_decode($row->pay_info, true);
            $pay_info = $row->pay_info;
            if ($row->pay_info['payment_method'] == 1) {
                $pay_info['payment_method'] = '微信支付';
            }elseif ($row->pay_info['payment_method'] == 2) {
                $pay_info['payment_method'] = '先用后付';
            }elseif ($row->pay_info['payment_method'] == 3) {
                $pay_info['payment_method'] = '抽奖商品0元订单';
            }elseif ($row->pay_info['payment_method'] == 4) {
                $pay_info['payment_method'] = '会员积分兑换订单';
            }
            $pay_info['prepay_time'] = date('Y-m-d H:i:s',$pay_info['prepay_time']);
            $pay_info['pay_time'] = date('Y-m-d H:i:s',$pay_info['pay_time']);
            $row->pay_info = $pay_info;
        }
        $row->create_time = date('Y-m-d H:i:s',$row->create_time);
        $row->update_time = date('Y-m-d H:i:s',$row->update_time);

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }
}